package com.kly.user.firebase;

import com.alibaba.fastjson.JSON;
import com.kly.user.config.NacosValueConfig;
import com.kly.user.firebase.bean.FirebaseEventTrackingReq;
import com.kly.user.utils.LittleOrangeService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import java.util.Collections;

@Slf4j
@Service
public class FirebaseEventTrackingService {
    private static final MediaType MEDIA_TYPE_JSON = MediaType.get("application/json; charset=utf-8");

    @Resource
    private NacosValueConfig nacosValueConfig;

    /**
     * events：一个由多个事件项构成的数组。您可以在一个请求中包含多个事件。
     * <p>
     * 若要在报告（如实时报告）中显示用户活动，必须将 engagement_time_msec 和 session_id 作为 event 的 params 的一部分提供。
     * engagement_time_msec 参数应反映事件的互动时间（以毫秒为单位）。
     */
    public boolean collect(String eventJson) {
        if (StringUtils.isEmpty(eventJson)) {
            return false;
        }
        JSONObject params = new JSONObject(eventJson);
        String eventName = params.getString("eventName");
        log.info("================Firebase埋点事件开始 {}", eventName);
        String currentTime = String.valueOf(System.currentTimeMillis());
        params.put("session_id", currentTime);
        params.put("engagement_time_msec", currentTime);

        FirebaseEventTrackingReq.FirebaseEvent event = FirebaseEventTrackingReq.FirebaseEvent.builder()
                .name(eventName)
                .params(params)
                .build();
        FirebaseEventTrackingReq req = FirebaseEventTrackingReq.builder()
                .client_id(nacosValueConfig.ppFirebaseEventTrackingClientId())
                .events(Collections.singletonList(event))
                .build();

        String url = nacosValueConfig.ppFirebaseEventTrackingUrl();
        String reqJson = JSON.toJSONString(req);

        log.info("================Firebase埋点事件上报 {}, {}, {}", eventName, url, reqJson);
        try {
            final String resp = LittleOrangeService.post(url, nacosValueConfig.ppFirebaseEventTrackingApiSecret(), reqJson);
            log.info("================Firebase埋点事件结束 {}, {}", eventName, resp);
            return true;
        } catch (Exception ex) {
            log.error("================Firebase埋点事件失败 {}", eventName, ex);
        }
        return false;
    }

    public boolean collect2(String eventJson) {
        if (StringUtils.isEmpty(eventJson)) {
            return false;
        }
        JSONObject params = new JSONObject(eventJson);
        String eventName = params.getString("eventName");
        log.info("================Firebase埋点事件开始 {}", eventName);
        String currentTime = String.valueOf(System.currentTimeMillis());
        params.put("session_id", currentTime);
        params.put("engagement_time_msec", currentTime);

        FirebaseEventTrackingReq.FirebaseEvent event = FirebaseEventTrackingReq.FirebaseEvent.builder()
                .name(eventName)
                .params(params)
                .build();
        FirebaseEventTrackingReq req = FirebaseEventTrackingReq.builder()
                .client_id(nacosValueConfig.ppFirebaseEventTrackingClientId())
                .events(Collections.singletonList(event))
                .build();

        String url = nacosValueConfig.ppFirebaseEventTrackingUrl();
        String reqJson = JSON.toJSONString(req);

        OkHttpClient httpClient = new OkHttpClient.Builder()
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                })
                .build();
        RequestBody body = RequestBody.create(reqJson, MEDIA_TYPE_JSON);
        Request request = new Request.Builder()
                .url(nacosValueConfig.ppFirebaseEventTrackingUrl())
                .post(body)
                .build();
        log.info("================Firebase埋点事件上报 {}, {}, {}", eventName, url, reqJson);
        try {
            Response response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                log.info("================Firebase埋点事件成功 {}, {}", eventName, JSON.toJSONString(response));
                return true;
            }
            log.error("================Firebase埋点事件失败 {}, {}", eventName, JSON.toJSONString(response));
        } catch (Exception ex) {
            log.error("================Firebase埋点事件失败 {}", eventName, ex);
        }
        return false;
    }

}
